package se.com.movie.reader.reader;

import java.io.File;

import se.com.movie.reader.model.Extension;
import se.com.movie.reader.model.Movie;
import se.com.movie.reader.model.Settings;
import se.com.movie.reader.writer.MovieWriter;

public class MovieReaderThread extends Thread implements Runnable {
	private File mRoot = null;
	private Settings mSettings = null;
	private MovieWriter mMovieWriter = null;
	private MovieReader mMovieReader = null;
	private int mDoneCount = 0;
	private static int HD_COUNT = 1;

	public MovieReaderThread(File root) {
		mSettings = Settings.getInstance();
		mMovieWriter = MovieWriter.getInstance();
		mMovieReader = MovieReader.getInstance();
		mRoot = root;
		mDoneCount = 0;
	}

	@Override
	public void run() throws NullPointerException {
		try {
			read(mRoot);
			System.out.println((HD_COUNT++) + "|done:" + mRoot.getPath() + " count:" + mDoneCount);
			mDoneCount = 0;
			getRoot();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void getRoot() {
		mRoot = mMovieReader.incrementRoot();
		if (mRoot != null) {
			int pos = mMovieReader.incretmentThreads();
			if (pos != -1) {
				mMovieReader.getThread()[pos] = new MovieReaderThread(mRoot);
				mMovieReader.getThread()[pos].start();
			} else {
				run();
			}
			getRoot();
		}
	}

	private void read(File file) {
		if (file.isFile()) {
			visit(file);
		} else if (file.isDirectory()) {
			try {
				for (File entity : file.listFiles()) {
					read(entity);
				}
			} catch (NullPointerException e) {
			}
		}
	}

	private void visit(File file) {
		// System.out.println(file.getName());
		if (mSettings.search(getFileExtension(file))) {
			// System.out.println(file.getName());
			++mDoneCount;
			mMovieWriter.write(readMovie(file));
		}
	}

	private Movie readMovie(File file) {
		Movie movie = new Movie();
		movie.setMovie(file.getName());
		movie.setPath(file.getPath());
		return movie;
	}

	private static Extension getFileExtension(File file) {
		int pos = file.getName().lastIndexOf('.');
		if (pos != -1) {
			if (file.getName().length() > pos + 1) {
				return new Extension(file.getName().substring(pos + 1));
			}
		}
		return new Extension("");
	}
}
